package com.example.demo.config.enter;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;

/**
 * spring securtiy 的异常都在这里改
 */
public class CustomSecuityError implements AuthenticationEntryPoint {

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException, ServletException {

		if (authException instanceof SessionAuthenticationException) {
			// 未登陆 401
			response.sendError(HttpStatus.UNAUTHORIZED.value(), "没有登陆");
		} else if (authException instanceof InsufficientAuthenticationException) {
			response.sendError(HttpStatus.UNAUTHORIZED.value(), "没有登陆，或没有权限访问");
		} else {
			// 500
			response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), authException.getMessage());
		}
	}
}
